<?php

namespace app\controller\admin;


use think\Request;
use app\eslib\EsUtils;

class Uploader
{
    const IMAGE_MIME = ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp'];
    const IMAGE_EXT = ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'];

    public function upload(Request $request)
    {
        $uploadedFiles = $request->file();
        if (!$uploadedFiles) {
            return json(EsUtils::stdMessage(false, '没有文件'));
        }
        $files=[];
        foreach($uploadedFiles as $item){
            if(is_array($item)){
                foreach($item as $item2){
                    $files[]=$item2;
                }
                continue;
            }
            $files[]=$item;
        }
        // 获取表单参数
        $imgWidth = $request->param('imgwidth/d', 0);
        $imgHeight = $request->param('imgheight/d', 0);
        $isMultipleFile = $request->param('is_multiple/d', 0) == 1;
        $isKeepName = $request->param('keep_name', 0) == 1;
        // 禁止上传 PHP 和 HTML 文件
        $forbiddenMimes = ['text/x-php', 'text/html', 'text/css', 'text/javascript', 'text/x-shellscript', 'application/x-javascript'];
        $forbiddenExts = ['php', 'html', 'htm', 'js', 'css'];

        $iniMaxSize =EsUtils::toBytes(ini_get('upload_max_filesize'));
        $data = [];
        try {
            foreach ($files as $file) {
                $fileName = $file->getOriginalName();
                if (!$file->isValid()) {
                    $data[] = '文件无效！文件：' . $fileName; // $file->getErrorMessage();
                    continue;
                }
                // 文件大小校验(2MB)
                if ($file->getSize() > $iniMaxSize) {
                    $data[] = '文件大小超过最大上传限制（'.EsUtils::formatBytes($iniMaxSize).'）。文件：' . $fileName;
                    continue;
                }
                if (in_array($file->getMime(), $forbiddenMimes) || in_array($file->getExtension(), $forbiddenExts)) {
                    $data[] =  '文件类型不允许上传。文件：' . $fileName;
                    continue;
                }
                //验证是否为图片文件
                if (in_array($file->getMime(), self::IMAGE_MIME)) {
                    $msgInfo = EsUtils::checkWidthAndHeight($file->getPathname(), $imgWidth, $imgHeight);
                    if (!$msgInfo['success']) {
                        $data[] = $msgInfo['message'];
                        continue;
                    }
                }
                // 上传到本地服务器（'https://picsum.photos/200/300'）
                $saveName = \think\facade\Filesystem::disk('uploads')->putFileAs(date('Y'), $file, ($isKeepName ? $fileName : $file->hashName('')));
                // 图片压缩
                // ...
                $filePath = '/uploads/' . str_replace('\\', '/', $saveName);
                $data[] = [
                    'original_name' => $fileName,
                    'path' => $filePath,
                    'size' => EsUtils::formatBytes($file->getSize()),
                ];
            }
            return json(EsUtils::stdMessage(true, '', $data));
        } catch (\Exception $ex) {
            return json(EsUtils::stdMessage(false, $ex->getMessage(), $ex));
        }
    }
}
